package com.iflytek.sbd.controller;

import com.alibaba.fastjson.JSON;
import jakarta.xml.bind.DatatypeConverter;


import java.security.MessageDigest;
import java.util.Arrays;

import java.util.List;
import java.util.TreeMap;

/**
 * @program: sbd
 * @description:
 * @author: 陈亮
 * @create: 2022-01-15 12:36
 */
public class ReqDedupHelper {

    /*
    @paramreq JSON请求的参数，这里通常是JSON*@paramexcludeKeys请求参数里面要去除哪些字段再求摘要*@return去除参数的MD5摘要
    */
    public static String dedupParamMD5(final String reqJSON, String... excludeKeys) {
        String decreptParam = reqJSON;
        TreeMap paramTreeMap = JSON.parseObject(decreptParam, TreeMap.class);
        if (excludeKeys != null) {
            List dedupExcludeKeys = Arrays.asList(excludeKeys);
            if (!dedupExcludeKeys.isEmpty()) {
                for (Object dedupExcludeKey : dedupExcludeKeys) {
                    paramTreeMap.remove(dedupExcludeKey);
                }
            }
        }
        String paramTreeMapJSON = JSON.toJSONString(paramTreeMap);
        String md5deDupParam = jdkMD5(paramTreeMapJSON);
        // log.debug("md5deDupParam={},excludeKeys={}{}", md5deDupParam, Arrays.deepToString(excludeKeys), paramTreeMapJSON);
        return md5deDupParam;
    }

    private static String jdkMD5(String src) {
        String res = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] mdBytes = messageDigest.digest(src.getBytes());
            res = DatatypeConverter.printHexBinary(mdBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
